import React, {Component} from 'react';
import {connect} from 'dva';
import {
    Button,
    Card,
    Cascader,
    Col,
    Form,
    Input,
    message,
    Modal,
    Popconfirm,
    Row,
    Select,
    Spin,
    Table,
    Tooltip
} from 'antd';
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import {FormattedMessage} from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";
import ChinaArea from "@/components/Tool/ChinaArea";
import router from "umi/router";

/**
 * 分页参数
 * @Author 肖家添
 * @Date 2019/8/22 15:09
 */
let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({customerModel}) => ({
    customerModel
}))
@Form.create()
class Customer extends Component {
    state = {
        loading: false,
        pageDataSource: [],
        selectedKeys: [],
        isShowEditModal: false,
        editData: {},
        employeeList: []
    };

    componentDidMount() {
        this.findPageDataSource();
        this.getSalerEmployee();
    }

    findPageDataSource = (e) => {
        let that = this, params = {...pagingData};
        if (e) {
            pagingData._current = 1;
            e.preventDefault();
        }
        const {form} = this.props;
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            params = {...params, ...values};
            let xstatus = params.xstatus;
            if (APP.isValidObj(xstatus)) {
                params.xstatus = parseInt(xstatus);
            }
            requestContinue();
        });

        function requestContinue() {
            const {dispatch} = that.props;
            APP.loading(that);
            dispatch({
                type: "customerModel/list",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(that);
                    if (data.success) {
                        const {list, pagination} = data.datas;
                        pagingData._current = pagination.current;
                        pagingData._pageSize = pagination.pageSize;
                        pagingData._total = pagination.total;
                        that.setState({
                            pageDataSource: list,
                            selectedKeys: []
                        });
                    }
                }
            });
        }
    };

    getDataById = () => {
        const {selectedKeys} = this.state;
        if (selectedKeys.length !== 1) return;
        const that = this,
            {dispatch} = that.props,
            id = selectedKeys[0];
        if (!APP.isValidObj(id)) return;
        APP.loading(that);
        dispatch({
            type: "customerModel/getCustomerById",
            payload: {id: id},
            callback: function (data) {
                that.setState({
                    loading: false,
                    editData: data.datas,
                    isShowEditModal: true
                });
            }
        });
    };

    enabledControl = (isEnabled) => {
        const { selectedKeys } = this.state;
        if(selectedKeys <= 0) return;
        const that = this, { dispatch } = this.props;
        APP.loading(that);
        dispatch({
            type: "customerModel/enabledControl",
            payload: {
                ids: selectedKeys.join(","),
                isEnabled: isEnabled
            },
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    message.success("操作成功");
                    that.findPageDataSource();
                }else{
                    message.error("操作失败！");
                }
            }
        });
    };

    exportData = (type) => {
        const {form} = this.props;
        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            let xstatus = params.xstatus;
            if (APP.isValidObj(xstatus)) {
                values.xstatus = parseInt(xstatus);
            }
            APP.exportData({
                parent: this,
                requestUrl: "/api/customer/exportData",
                fileNamePrefix: "客户",
                exportType: type,
                tablePagination: pagingData,
                formData: values
            });
        });
    };

    render() {
        const that = this;
        const {
            loading,
            pageDataSource,
            selectedKeys
        } = that.state;
        const {form} = that.props;
        const {getFieldDecorator} = form;
        return (
            <Spin spinning={loading}>
                <PageHeaderWrapper title={<FormattedMessage id="menu.customer"/>}>
                    <Card style={{marginBottom: 15}}>
                        <Form layout="inline" onSubmit={this.findPageDataSource}>
                            <Row>
                                <Col span={8}>
                                    <Form.Item label="客户姓名">
                                        {getFieldDecorator('oname', {})(<Input placeholder="请输入客户姓名"
                                                                               allowClear={true}/>)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="联系人">
                                        {getFieldDecorator('contacts', {})(<Input placeholder="请输入联系人"
                                                                                  allowClear={true}/>)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="联系电话">
                                        {getFieldDecorator('tel', {})(<Input placeholder="请输入联系电话" allowClear={true}/>)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="跟进状态">
                                        {getFieldDecorator('xstatus', {})(
                                            <Select placeholder={"请选择跟进状态"} allowClear={true} style={{width: 174}}>
                                                <Select.Option value="">全部</Select.Option>
                                                <Select.Option value={1}>待跟进</Select.Option>
                                                <Select.Option value={2}>已跟进</Select.Option>
                                                <Select.Option value={3}>已签单</Select.Option>
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col style={{textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20}}>
                                    <Button type="primary" htmlType="submit" {...APP.buttonsStyle_MR15}>
                                        查找
                                    </Button>
                                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                                        this.exportData(1);
                                    }}>
                                        导出本页
                                    </Button>
                                    <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                                        this.exportData(2);
                                    }}>
                                        导出所有
                                    </Button>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card style={{marginBottom: 15}}>
                        <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                            this.setState({isShowEditModal: true});
                        }}>
                            新增
                        </Button>
                        <Tooltip
                            title={selectedKeys.length === 1 ? '' : '请选中一行数据'}
                        >
                            <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                                this.getDataById();
                            }}>
                                编辑
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定删除选中数据吗？"
                                onConfirm={() => {
                                    this.enabledControl(-1);
                                }}
                                okText="删除"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...APP.buttonsStyle_MR15}>
                                    删除
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                        <Button type="primary" {...APP.buttonsStyle_MR15} onClick={() => {
                            router.push({
                                pathname: '/journal/editJournal',
                                state: { }
                            });
                        }}>
                            发布期刊
                        </Button>
                    </Card>
                    <Card>
                        <Table
                            bordered
                            rowKey={data => `${data.id}`}
                            rowSelection={APP.tableRowSelection(function (selectedRowKeys, selectedRows) {
                                that.setState({selectedKeys: selectedRowKeys});
                            }, selectedKeys)}
                            columns={this.columns}
                            dataSource={pageDataSource}
                            pagination={{
                                pageSize: pagingData._pageSize,
                                current: pagingData._current,
                                total: pagingData._total,
                                onChange: (page, pageSize) => {
                                    pagingData._current = page;
                                    this.findPageDataSource();
                                },
                                showTotal: total => `共 ${total} 条数据`,
                            }}
                        />
                    </Card>
                    <EditForm parent={this}/>
                </PageHeaderWrapper>
            </Spin>
        )
    }

    columns = [{
        title: '运营商',
        dataIndex: 'operatorName',
        key: 'operatorName',
    }, {
        title: '客户名称',
        dataIndex: 'oname',
        key: 'oname',
    }, {
        title: '联系人',
        dataIndex: 'contacts',
        key: 'contacts',
    }, {
        title: '联系电话',
        dataIndex: 'tel',
        key: 'tel',
    }, {
        title: '邮箱',
        dataIndex: 'email',
        key: 'email',
    }, {
        title: '所在省市',
        dataIndex: 'areaName',
        key: 'areaName',
    }, {
        title: '详细地址',
        dataIndex: 'address',
        key: 'address',
    }, {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
    }, {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
    }, {
        title: '销售员',
        dataIndex: 'salerName',
        key: 'salerName',
    }];

    getSalerEmployee() {
        const {dispatch} = this.props;
        const that = this;
        const params = {
            postId: 2
        };
        dispatch({
            type: "pointModel/getEmployeeList",
            payload: params,
            callback: function (data) {
                if (data.success) {
                    that.setState({
                        employeeList: data.datas
                    });
                }
            },
        });
    }

    getEmployeeOptions() {
        const {employeeList} = this.state;
        return employeeList.map(item => (
            <Select.Option key={item.id} value={item.id}>
                {item.name}
            </Select.Option>
        ));
    }
}

const EditForm = Form.create()(props => {
    let {parent, form} = props;
    const {dispatch} = parent.props;
    const {loading, isShowEditModal, editData} = parent.state;
    const formItemLayout = {
        style: {
            margin: '0px',
        },
    };
    const {getFieldDecorator} = form;
    //-- 地区默认选中地址
    const areaDefaultValues = new Array();
    if (editData.id) {
        const {provinceId, cityId, areaId} = editData;
        for (const id of [provinceId, cityId, areaId]) {
            if (APP.isValidObj(id)) {
                areaDefaultValues.push(id.toString());
            }
        }
    }

    //-- 显示/隐藏 数据编辑窗口
    function handlerEditModal() {
        form.resetFields();
        let {isShowEditModal, editData} = parent.state;
        isShowEditModal = !isShowEditModal;
        editData = {};
        parent.setState({isShowEditModal, editData});
    }

    const colFloatRight = {
        style: {
            float: 'right'
        },
    };
    const titleLabel = {
        style: {
            color: "rgba(0, 0, 0, 0.85)",
            padding: '0 0 8px'
        }
    };

    function submit() {
        form.validateFields((err, values) => {
            if (err) return;
            APP.validNilParams(values);
            const area = values.area;
            if (area) {
                delete values.area;
                if (area.length >= 1) {
                    values.provinceId = parseInt(area[0]);
                }
                if (area.length >= 2) {
                    values.cityId = parseInt(area[1]);
                }
                if (area.length >= 3) {
                    values.areaId = parseInt(area[2]);
                }
            }
            if (!/^[\u4e00-\u9fa5]{2,20}$/.test(values.oname)) {
                message.error('请输入2-20个中文字符的客户名称');
                return;
            } else if (!/^[\u4e00-\u9fa5]{2,20}$/.test(values.contacts)) {
                message.error('请输入2-20个中文字符的联系人');
                return;
            } else if (!/^[1][3,4,5,7,8][0-9]{9}$/.test(values.tel)) {
                message.error('请输入正确的联系电话');
                return;
            } else if (!/^[\u4e00-\u9fa5\w#]{2,20}$/.test(values.address)) {
                message.error('请输入2-20个字符的详细地址');
                return;
            } else if (APP.isValidObj(values.email) && !/^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/.test(values.email)) {
                message.error('请输入正确的邮箱');
                return;
            }
            request(values);
        });

        function request(params) {
            APP.loading(parent);
            dispatch({
                type: "customerModel/saveCustomer",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(parent);
                    if (data.success) {
                        message.success("保存成功！");
                        parent.findPageDataSource();
                        handlerEditModal();
                    } else {
                        message.error(data.msg);
                    }
                }
            });
        }
    }

    return (
        <Modal
            title={<FormattedMessage id="menu.customer.editCustomer"/>}
            visible={isShowEditModal}
            onOk={() => submit()}
            onCancel={() => handlerEditModal()}
            okText="保存"
            cancelText='返回'
            confirmLoading={loading}
        >
            <Form layout="vertical">
                {getFieldDecorator('id', {initialValue: editData.id})(<Input hidden={true}/>)}
                <Row>
                    <Form.Item label="客户名称" {...formItemLayout}>
                        {getFieldDecorator('oname', {
                            initialValue: editData.oname,
                            rules: [
                                {
                                    required: true,
                                    message: '请输入客户名称！',
                                },
                            ],
                        })(<Input placeholder="请输入客户名称" allowClear={true}/>)}
                    </Form.Item>
                </Row>
                <Row>
                    <Col span={11}>
                        <Form.Item label="联系人" {...formItemLayout}>
                            {getFieldDecorator('contacts', {
                                initialValue: editData.contacts,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入联系人！',
                                    },
                                ],
                            })(<Input placeholder="请输入联系人" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                    <Col span={11} {...colFloatRight}>
                        <Form.Item label="联系电话" {...formItemLayout}>
                            {getFieldDecorator('tel', {
                                initialValue: editData.tel,
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入联系电话！',
                                    },
                                ],
                            })(<Input placeholder="请输入联系电话" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <div className={"ant-form-item-required"} {...titleLabel}>客户联系地址</div>
                    <Col span={15}>
                        <Form.Item style={{marginRight: 4, marginBottom: 0}}>
                            {
                                getFieldDecorator('area', {
                                    initialValue: areaDefaultValues,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请选择城市！',
                                        },
                                    ],
                                })(<Cascader placeholder={"请选择城市"} options={ChinaArea} allowClear={true}/>)
                            }
                        </Form.Item>
                    </Col>
                    <Col span={9}>
                        <Form.Item {...formItemLayout}>
                            {
                                getFieldDecorator('address', {
                                    initialValue: editData.address,
                                    rules: [
                                        {
                                            required: true,
                                            message: '请输入详细地址！',
                                        },
                                    ],
                                })(<Input placeholder={"请输入详细地址"} allowClear={true}/>)
                            }
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={11}>
                        <Form.Item label="销售员" {...formItemLayout}>
                            {
                                getFieldDecorator('salerId', {
                                    initialValue: editData.salerId,
                                })(
                                    <Select placeholder={"请选择销售员"} allowClear={true}>
                                        {parent.getEmployeeOptions()}
                                    </Select>
                                )
                            }
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Col span={11}>
                        <Form.Item label="邮箱" {...formItemLayout}>
                            {getFieldDecorator('email', {
                                initialValue: editData.email,
                                rules: [
                                    {
                                        message: '请输入邮箱！',
                                    },
                                ],
                            })(<Input placeholder="请输入邮箱" allowClear={true}/>)}
                        </Form.Item>
                    </Col>
                </Row>
                <Row>
                    <Form.Item label="备注" {...formItemLayout}>
                        {
                            getFieldDecorator('remark', {
                                initialValue: editData.remark,
                            })(
                                <Input.TextArea
                                    placeholder="请输入备注"
                                    className="custom"
                                    style={{
                                        height: 150,
                                        width: "100%",
                                        resize: 'none'
                                    }}
                                />
                            )
                        }
                    </Form.Item>
                </Row>
            </Form>
        </Modal>);
});

export default Customer;
